<template>
  <el-container>
    <div class="row_block">
      <el-card class="box-card" style="width: 800px">
        <div slot="header" class="clearfix" >
          <el-button type="shenda" size="small" icon="el-icon-back" style="float: right" @click="goBack">返回</el-button>
          <span >批量入库</span>

        </div>
        <el-form :model="form" ref="form" :rules="rules" label-width="150px">
          <el-form-item label="上游公司" prop="channelCompany">
            <el-select size="small" placeholder="上游公司" v-model="form.channelCompany" @change="changeChannelCompany" style="width: 300px;">
              <el-option v-for="item in form.channelcompanyListSelect" :key="item.value" :label="item.label" :value="item"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="运营商" prop="dictCardOperator">
            <el-radio-group v-model="form.dictCardOperator" @change="changeOperator">
              <el-radio label="CARDTELECOM">电信</el-radio>
              <el-radio label="CARDMOBILE">移动</el-radio>
              <el-radio label="CARDUNICOM">联通上传</el-radio>
              <el-radio label="FLOWPOOL">其他</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="卡号" prop="cardNumberType" v-if="(form.channelCompany.dictOperator==='UNICOM'||form.channelCompany.dictOperator==='LIANTONGWULIAN'||form.channelCompany.dictOperator=='LIANTONGJIYUEHUA')&&form.dictCardOperator!=='FLOWPOOL'" style="width: 600px">
            <el-select size="small" style="width: 300px;" v-model="form.cardNumberType">
              <el-option label="去掉末尾数字" value="1"></el-option>
              <el-option label="EXCEL第二列" value="2"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="选择账号" prop="accountId" >
            <el-select size="small" placeholder="选择账号" style="width: 300px;" v-model="form.accountId">
              <el-option v-for="account in form.accountSelect" :key="account.id" :label="account.accountName" :value="account.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="卡状态" prop="dictChannelCardStatus" v-if="(dictOperator==='TELECOM' || dictOperator==='XIAOXIANG')&&form.dictCardOperator!=='FLOWPOOL'" style="width: 600px">
            <el-radio-group v-model="form.dictChannelCardStatus">
              <el-radio label="ACTIVATE">已激活</el-radio>
              <el-radio label="DEACTIVATE">去激活</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="上传卡号" prop="fileName" v-if="form.channelCompany.dictOperator==='UNICOM'||form.channelCompany.dictOperator==='CMPTELECOM'||form.channelCompany.dictOperator==='LIANTONGWULIAN'|| form.dictCardOperator==='FLOWPOOL'||form.channelCompany.dictOperator=='LIANTONGJIYUEHUA'">
            <el-upload
              class="upload-demo"
              action="#"
              :before-upload="uploadCards"
              :limit="1">
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">{{form.fileName}}</div>
            </el-upload>
            <el-button type="success" @click="getModulLT" size="small" v-if="(form.channelCompany.dictOperator==='UNICOM'||form.channelCompany.dictOperator==='LIANTONGWULIAN'||form.channelCompany.dictOperator=='LIANTONGJIYUEHUA')&&form.dictCardOperator!=='FLOWPOOL'">下载联通摸板</el-button>
            <el-button type="success" @click="getModulDX" size="small" v-if="form.channelCompany.dictOperator==='CMPTELECOM'">下载电信CMP摸板</el-button>
            <el-button type="shenda" size="small" @click="downLoadShuolangMuban" :loading="loading" v-if="form.dictCardOperator=='FLOWPOOL'"> 下载导入模板<i class="el-icon-download el-icon--right" ></i></el-button>
          </el-form-item>
          <el-form-item label="连号类型" prop="type" v-if="form.channelCompany.dictOperator!=='UNICOM'&&form.channelCompany.dictOperator!=='CMPTELECOM'&&form.channelCompany.dictOperator!=='LIANTONGWULIAN'&&form.dictCardOperator!=='FLOWPOOL'&&form.channelCompany.dictOperator!=='LIANTONGJIYUEHUA'">
            <el-radio label="1" v-model="form.type" >ICCID(连号+字母)</el-radio>
            <el-radio label="2" v-model="form.type" >ICCID(固定头部+尾部连号)
            </el-radio>
            <div v-if="form.type==='1'" style="margin: 10px 0" >
              <span>头部连号：</span>
              <el-input v-model.trim="form.typeOneStartIccId" style="width: 200px"></el-input>
              <span style="margin: 0 10px">至</span>
              <el-input v-model.trim="form.typeOneEndIccId" style="width: 200px"></el-input>
            </div>
            <div v-if="form.type==='1'" style="margin: 10px 0">
              <span>尾号字母：</span>
              <el-input v-model.trim="form.endIccId" style="width: 200px"></el-input>
            </div>
            <div v-if="form.type==='2'" style="margin: 10px 0">
              <span>固定头部：</span>
              <el-input v-model.trim="form.preLetter" style="width: 200px"></el-input>
            </div>
            <div v-if="form.type==='2'" style="margin: 10px 0">
              <span>尾部连号：</span>
              <el-input v-model.trim="form.typeTwoStartIccId" style="width: 200px"></el-input>
              <span style="margin: 0 10px">至</span>
              <el-input v-model.trim="form.typeTwoEndIccId" style="width: 200px"></el-input>
            </div>
          </el-form-item>
          <el-form-item label="卡体类型" prop="bodyType" v-if="form.dictCardOperator!=='FLOWPOOL'">
            <el-select size="small" placeholder="卡体类型" style="width: 300px;" v-model="form.bodyType">
              <el-option v-for="(card, index) in form.bodyTypeSelect" :key="index" :label="card.label"
                         :value="card.value"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="卡类型" prop="dictCardType" v-if="form.dictCardOperator!=='FLOWPOOL'">
            <el-radio-group v-model="form.dictCardType">
              <el-radio label="CARD_SHARE">共享</el-radio>
              <el-radio label="CARE_NOT_SHARE">非共享</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="定向选择" prop="dictChoseDirect" v-if="form.dictCardOperator!=='FLOWPOOL'">
            <el-radio-group v-model="form.dictChoseDirect">
              <el-radio label="CARD_DIRECT">定向</el-radio>
              <el-radio label="CARD_NOT_DIRECT">非定向</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="套餐" prop="primeval" v-if="form.dictCardOperator!=='FLOWPOOL'">
            <el-input size="small" v-model="form.primeval" style="width: 300px">
              <el-select class="isl" slot="append" size="small" v-model="form.unit" placeholder="单位"
                         style="width: 80px;">
                <el-option label="GB" value="G"></el-option>
                <el-option label="MB" value="M"></el-option>
              </el-select>
            </el-input>
          </el-form-item>
          <el-form-item label="静默日期" prop="dateType" v-if="form.dictCardOperator!=='FLOWPOOL'">
            <el-radio-group v-model="form.dateType" @change="changeDateType">
              <el-radio-button label="3">3个月</el-radio-button>
              <el-radio-button label="6">6个月</el-radio-button>
              <el-radio-button label="12">12个月</el-radio-button>
            </el-radio-group>
            <div style="margin: 10px 0">
              <span>{{form.nowData}}</span>
            </div>
          </el-form-item>
          <el-form-item label="起始业务号码" prop="insNumber" v-if="form.channelCompany.dictOperator!=='UNICOM'&&form.channelCompany.dictOperator!=='CMPTELECOM'&&form.channelCompany.dictOperator!=='LIANTONGWULIAN'&&form.dictCardOperator!=='FLOWPOOL'&&form.channelCompany.dictOperator!=='LIANTONGJIYUEHUA'">
            <el-input v-model.trim="form.insNumber" type="text" min="0" max="2147483648" style="width: 300px"></el-input>
          </el-form-item>
          <el-form-item label="apn" prop="apn" v-show="form.channelCompany.dictOperator!=='UNICOM'&&form.channelCompany.dictOperator!=='CMPTELECOM'&&form.channelCompany.dictOperator!=='LIANTONGWULIAN'&&form.dictCardOperator!=='FLOWPOOL'&&form.channelCompany.dictOperator!=='LIANTONGJIYUEHUA'">
            <el-input size="small" style="width: 300px;" v-model="form.apn"></el-input>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" v-preventReClick @click="submitHandles('form')">提交</el-button>
            <el-button v-preventReClick @click="resetForm('form')">重置</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>
  </el-container>
</template>

<script>
  import {singleCardStorage, batchInventory, batchInventoryUnicom, listAccountByChannelCompanyId} from '@/api/getData'

  export default {
    name: 'BatchStockIndex',
    data() {
      return {
        pagekey: '',
        rules: {
          channelCompany: [{required: true, message: '请选择上游公司',}],
          dictCardOperator: [{required: true, message: '请选择运营商',}],
          bodyType: [{required: true, message: '请选择卡体类型',}],
          numRule: [{required: true, message: '请选择系统生成业务号码',}],
          accountId: [{required: true, message: '请选择账号',}],
          dictChoseDirect: [{required: true, message: '请选择定向/非定向', trigger: 'change'}],
          insNumber: [{required: true, message: '请输入业务号码起始字段',}],
          primeval: [
            {required: true, message: '请输入套餐',},
            {pattern: /^(([1-9][0-9]*)|(([0]\.\d{0,1}|[1-9][0-9]*\.\d{0,1})))$/, message: '请输入数字,精确到小数点后一位',}
          ],
          nowData: [
            {required: true, message: '请选择静默日期',}
          ],
          unit: [
            {required: true, message: '请选择套餐单位',}
          ],
          type: [
            { validator: (rule, value, callback)=>{
                if(value==1){
                  if(!this.form.typeOneStartIccId || !this.form.typeOneEndIccId || !this.form.endIccId){
                    return callback('请将头部连号或尾号字母信息填写完整');
                  }
                  if(this.form.typeOneStartIccId > this.form.typeOneEndIccId){
                    return callback('结束ICCID必须大于起始ICCID');
                  }
                  this.form.typeTwoStartIccId = '';
                  this.form.typeTwoEndIccId = '';
                  this.form.preLetter = '';
                  callback();
                }
                else if(value==2){
                  if(!this.form.preLetter || !this.form.typeTwoStartIccId || !this.form.typeTwoStartIccId){
                    return callback('请将固定头部或头部连号信息填写完整');
                  }
                  if(this.form.typeTwoStartIccId > this.form.typeTwoEndIccId){
                    return callback('结束ICCID必须大于起始ICCID');
                  }
                  this.form.typeOneStartIccId = '';
                  this.form.typeOneEndIccId = '';
                  this.form.endIccId = '';
                  this.form.nowDate = new Date();
                  callback();
                }
                else{
                  callback();
                }
              }}
          ],
          cardNumberType: [
            {required: true, message: '请选择卡号操作方式'}
          ],
          dateType: [
            { required: true, message: '请选择静默日期时间长度类型'}
          ]
        },
        dictChannelCardStatus: 'ACTIVATE',
        form: {
          channelCompany: {},
          bodyType: '',
          bodyTypeSelect: [],
          channelcompanyList: [],
          channelcompanyListSelect: [],
          nowData: '',
          numRules: [],
          numRulesSelect: [],
          startIccId: '',
          endIccId: '',
          primeval: '',
          endLetter: '',
          preLetter: '',
          dictChoseDirect: '',
          dictCardType: '',
          typeOneStartIccId: '',
          typeOneEndIccId: '',
          typeTwoStartIccId: '',
          typeTwoEndIccId: '',
          dictChannelCardStatus: 'DEACTIVATE',
          accountSelect: [],
          accountId: '',
          quietPeriodDate: '',
          insNumber: '',
          unit: "G",
          dictCardOperator: 'CARDTELECOM',
          apn: "",
          dateType: '',
          type: "1",
          fileName: ''
        },
        active: 1,
        dictOperatorName: '',
        currentNum: '',
        endIccId: '',
        dictOperator: '',
        errorReason: '',
        loading: false,
        unitSelect: [
          {
            value: 'G',
            label: 'GB'
          },
          {
            value: 'M',
            label: 'MB'
          }
        ],

      }
    },
    async created() {
      this.pagekey = await this.$getPageKey();
      this.initData();

    },

    methods: {
      goBack() {
        this.$router.back(-1)
      },
      submitHandles(form) {
        this.errorReason = '';
        let mb = 0;
        if (this.form.unit === 'G') {
          mb = this.form.primeval * 1024
        } else {
          mb = this.form.primeval
        }

        let channelCompanyId = this.form.channelCompany.value;
        this.$refs[form].validate(async (valid) => {
          if (valid) {
            let cardNumberType = this.form.dictCardOperator === "CARDUNICOM" ? this.form.cardNumberType : '';
            let startIccId = this.form.type == 1 ? this.form.typeOneStartIccId : this.form.typeTwoStartIccId;
            let endIccId = this.form.type == 1 ? this.form.typeOneEndIccId : this.form.typeTwoEndIccId;

            let params = {
              channelCompanyId: channelCompanyId,
              dictCardOperator: this.form.dictCardOperator,
              accountId: this.form.accountId,
            };
            if(this.form.dictCardOperator!=='FLOWPOOL'){
              params.dictCardBodyType = this.form.bodyType
              params.dictCardType = this.form.dictCardType
              params.dictChoseDirect = this.form.dictChoseDirect
              params.primeval = mb
              params.quietPeriodDateStr = this.form.nowData+' 23:59:59'
              params.cardNumberType = cardNumberType
              params.beginIccId = startIccId
              params.finalIccId = endIccId
              params.type = this.form.type
              params.endLetter = this.form.endIccId
              params.preLetter = this.form.preLetter
              params.dictChannelCardStatus = this.form.dictChannelCardStatus
              params.insNumber = this.form.insNumber
              params.apn = this.form.apn
            }
            if (this.form.file !== undefined && this.form.file) {
              params.file = this.form.file
            }
            else if ((this.form.channelCompany.value === '14'|| this.form.dictCardOperator=='FLOWPOOL') && !this.form.file) {
              this.$alert('请选择Excel文件', '提示', {
                confirmButtonText: '确定',
                callback: action => {

                }
              });
              return false;
            }
            //测试  联通执行小宇新接口
            const b = await batchInventoryUnicom(params, {
              pagekey: this.pagekey
            });

            if (b._result) {
              this.$confirm('数据已提交，批量入库中， 是否立即跳转至入库记录查看结果?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
              }).then(() => {
                this.$router.push({
                  path: '/Stock/stockInList'
                })
              }).catch(() => {
                this.resetForm(form);
              });
            }
            this.pagekey = await this.$getPageKey();
          }
        })
      },
      resetForm(formName){
        this.$refs[formName].resetFields();
        this.form.typeOneStartIccId = '';
        this.form.typeOneEndIccId = '';
        this.form.endIccId = '';
        this.form.typeTwoStartIccId = '';
        this.form.typeTwoEndIccId = '';
        this.form.preLetter = '';
        this.form.channelCompany = {};
        this.form.nowData = this.dateFormate.formate(0);
        this.form.unit = 'G';
        this.$refs[formName].resetFields();
      },

      //切换静默期
      changeDateType(val){
        this.form.dateType = val;
        this.form.nowData = this.dateFormate.formate(parseInt(val));
      },
      async initData() {
        const returnData = await singleCardStorage({})
        if (returnData._result) {
          returnData.data.channelcompanyList.forEach(item => {
            this.form.channelcompanyListSelect.push({
              value: item.id,
              label: item.operatorBranch,
              dictOperator: item.dictOperator
            })
          });
          for (let s in returnData.data.bodyType) {
            this.form.bodyTypeSelect.push({value: s, label: returnData.data.bodyType[s]})
          }
          this.form.nowData = returnData.data.nowData;
          if (returnData.data.numRules) {
            returnData.data.numRules.forEach(item => {
              this.form.numRulesSelect.push({id: item.id, name: item.name})
            })
          }
        }
      },


      async changeChannelCompany(val) {
        this.$refs['form'].clearValidate();
        this.form.accountId = '';
        this.form.channelCompany = val;
        let list = await listAccountByChannelCompanyId({
          channelCompanyId: val.value
        });
        if (list._result) {
          this.form.accountSelect = list.data
        }
        if (val.dictOperator === 'CHINAMOBILE') {
          this.form.dictCardOperator = 'CARDMOBILE';
        }
        else if (val.dictOperator === 'UNICOM'||val.dictOperator==='LIANTONGWULIAN'||val.dictOperator==='LIANTONGJIYUEHUA') {
          this.form.dictCardOperator = 'CARDUNICOM';
        }
        else if (val.dictOperator === 'FLOWPOOL' ||val.dictOperator==='TIANYU'){
          this.form.dictCardOperator = 'FLOWPOOL';
        }
        else{
          this.form.dictCardOperator = 'CARDTELECOM';
        }

      },

      uploadCards(file) {
        this.form.file = file;
        if (file) {
          this.form.fileName = file.name;
        }
      },
      getModulLT() {
        window.location.href = 'https://imgsd.1688iot.vip/unicom_template.xlsx';
      },
      getModulDX() {
        window.location.href = 'https://imgsd.1688iot.vip/%E7%94%B5%E4%BF%A1CMP%E5%85%A5%E5%BA%93%E6%A8%A1%E6%9D%BF.xlsx';
      },
      changeOperator(val) {
        this.form.dictCardOperator = val;
       // this.form.channelCompany = {};
        for (let item of this.form.channelcompanyListSelect) {
          if (val === 'CARDTELECOM' && item.label.indexOf('电信') > -1) {
            this.changeChannelCompany(item);
            break;
          }
          else if (val === 'CARDMOBILE' && item.label.indexOf('移动') > -1) {
            this.changeChannelCompany(item);
            break;
          }
          else if (val === 'CARDUNICOM' && item.label.indexOf('联通') > -1) {
            this.changeChannelCompany(item);
            break;
          }
         /* else if (val === 'FLOWPOOL' && item.label.indexOf('岱川') > -1) {
            this.changeChannelCompany(item);
            break;
          }*/
        }

      },
      downLoadShuolangMuban(){
        let href = "https://imgsd.1688iot.vip/%E9%80%9A%E7%94%A8%E5%85%A5%E5%BA%93%E6%A8%A1%E6%9D%BF.xlsx";
        window.open(href, '_blank');
      },
      keyChangeHandle(fileList) {
        if (fileList !== '') {
          return false
        } else {
          this.fileList.excel = this.$refs.key.files[0]
          if (this.$refs.key.files[0] != null) {
            this.fileName = this.$refs.key.files[0].name;
            this.fileType = this.fileName.substring(this.fileName.lastIndexOf('.')+1,this.fileName.length);
          }
        }
      },
    }
  }
</script>

<style scoped lang="scss">
  .link_class {
    color: #1890ff;
    cursor: pointer;
  }

  .el-header {
    margin-top: 5vh;
  }

  .el-main {
    .el-form {
      .button /deep/ .el-col {
        display: flex;
        justify-content: flex-start;
      }

      .box /deep/ label {
        text-align: left;
      }

      .sale /deep/ label {
        letter-spacing: 7px;
      }
    }
  }

  .el-popper[x-placement^=top] {
    box-shadow: 0px 0px 10px #888888;
    margin-left: 6px;
    margin-right: -39px;

    button {
      display: block;
    }

    .operation {
      border: 0;
      outline: none;
      display: block;
      text-align: center;
      margin: 0;
    }
  }

  .file_upload_box {
    display: inline-block;
    width: 200px;
    height: auto;
    position: relative;
    overflow: hidden;
  }

  .file_upload_box input[type=file] {
    position: absolute;
    left: 0;
    top: 6px;
    width: 100px;
    line-height: 25px;
    opacity: 0;
    cursor: pointer;
  }

  .file_upload_box a {
    display: inline-block;
    width: 50%;
    line-height: 25px;
    text-align: center;
    font-family: "Microsoft yahei";
    background-color: #315baf;
    color: #FFF;
    font-weight: 700;
    text-decoration: none;
  }
  .row_block {
    width: 100%;
    height: 100%;
    position: relative;
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 70px 0;
  }
</style>
